package com.mdx.core.impl;

import com.mdx.api.entity.CommunityUser;
import com.mdx.api.service.CommunityUserService;
import com.mdx.api.util.ResultVo;
import com.mdx.api.vo.LoginVo;
import com.mdx.rest.security.JWTProvider;
import com.mdx.rest.service.MyUserDetailsService;
import com.mdx.tools.util.StringUtils;
import com.mdx.tools.util.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;


/**
 * @author : jiagang
 * @date : Created in 2022/2/10 17:29
 */

@Slf4j
@Service
public class CommunityUserServiceImpl implements CommunityUserService {

    @Autowired
    private MyUserDetailsService myUserDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JWTProvider jwtProvider;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    /**
     * 登录
     * @param communityUser
     * @return
     */
    @Override
    public ResultVo login(CommunityUser communityUser) {
        try {

            // 登录
            UserDetails userDetails = myUserDetailsService.loadUserByUsername(communityUser.getUsername());

            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

            // 判断用户名密码是否正确
            if (StringUtils.isEmpty(userDetails.getUsername()) ||
                    ! encoder.matches(communityUser.getPassword(), userDetails.getPassword())){
                return ResultVo.error("用户名或者密码不正确");
            }
            // 把登录信息存到全局
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);

            // 生成token
            String token = jwtProvider.generateToken(userDetails);

            LoginVo loginVo = new LoginVo();
            loginVo.setToken("Bearer " + token);

            return ResultVo.success(loginVo);

        }catch (Exception e){
            log.error("登录异常:",e);
            throw new BusinessException("登录失败",e);
        }
    }
}
